package com.zxcz.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.redisson.api.RList;
import org.redisson.api.RListMultimap;
import org.redisson.api.RLock;
import org.redisson.api.RScoredSortedSet;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aliyuncs.iot.model.v20180120.RegisterDeviceResponse;
import com.zxcz.aliyun.IotConfig;
import com.zxcz.aliyun.IotManager;
import com.zxcz.domain.Devices;
import com.zxcz.domain.Firmware;
import com.zxcz.domain.IotProduct;
import com.zxcz.domain.PageResult;
import com.zxcz.domain.Resource;
import com.zxcz.domain.Result;
import com.zxcz.domain.User;
import com.zxcz.mapper.DevicesMapper;
import com.zxcz.mapper.IotProductMapper;
import com.zxcz.redis.RedisManager;
import com.zxcz.service.DevicesService;
import com.zxcz.tools.Constants;
import com.zxcz.tools.CustomHttpStatus;
import com.zxcz.tools.RedisKeyBuilder;
import com.zxcz.tools.ResultUtil;

@Service
@Transactional
public class DevicesServiceImpl implements DevicesService{
	@Autowired
	private DevicesMapper devicesMapper;
	@Autowired
	private IotProductMapper iotProductMapper;
	@Autowired 
	private IotManager iotManager;
	@Autowired
	private IotConfig iotConfig;
	@Autowired
	private RedissonClient redisson;
	private static final Log logger = LogFactory.getLog(DevicesServiceImpl.class);

	/**
	 * 分页
	 */
	@Override
	public PageResult<Devices> findPage(int pageNum, int pageSize, String deviceId, String mac, String account) {
		// 起始位置
		int pageNumber = (pageNum-1) * pageSize;
		List<Devices> deviceList = devicesMapper.queryDevicesCondition(pageNumber, pageSize, deviceId, mac, account);
		Long total = devicesMapper.getTotal(deviceId, mac, account);
		
		//返回分页数据
		PageResult<Devices> pageResult = new PageResult<Devices>();
		pageResult.setRows(deviceList);
		pageResult.setTotal(total);
		
		return pageResult;
	}

	/**
	 * 添加指定用户id和数量的设备
	 * @param user 用户
     * @param deviceCount 设备数量(用户定义)
     * @return List<Devices> 返回创建的设备集合
	 */
	@Override
	public List<Devices> addDevicesNum(User user, int deviceCount) {
		RLock rLock = redisson.getLock("deviceLock");
		//存储创建设备的集合
		List<Devices> deviceList = new ArrayList<>();
		try {
			boolean res = rLock.tryLock(10, 5, TimeUnit.SECONDS);
			if(res) {
				//获取所属产品
				IotProduct iotProduct = iotProductMapper.findIotProductById(user.getIotProductId());
				//插入deviceCount条数据
				for(int count=0;count<deviceCount;count++) {
					//生成12位随机大写字母和数字
					String did = getRandomString(12);
					int num = 0;
					
					while(num == 0) {
						Devices devices = new Devices();
						devices.setDid(did);
						devices.setCreatedAt(new Date());
						devices.setUpdatedAt(new Date());
						devices.setUserId(user.getId());
						//添加到数据库
						num = devicesMapper.addDevicesIfNotExist(devices);
						if(num == 0) {
							did = getRandomString(12);
						}else {
							//存到集合返回
							deviceList.add(devices);
						}
					}
					
					//判断用户选择的产品在数据库中是否有对应产品存在
					if(iotProduct != null) {
						//  阿里云平台注册设备
//						RegisterDeviceResponse response = iotManager.registerDevice(iotProduct.getProductKey(), did);
					}
				} // for
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			rLock.unlock();
		}
		
		return deviceList;
		
	}
	
	/**
	 * 生成指定长度的随机大写字母和数字组合字符串
	 * @param length 需要生成的随机位数
	 * @return String
	 */
	public String getRandomString(int length) {
		String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random=new Random();
	    StringBuffer sb=new StringBuffer();
	    for(int i=0;i<length;i++){
	    	int number=random.nextInt(36);
	    	sb.append(str.charAt(number));
	    }
	    return sb.toString();
	}

	@Override
	public void deleteDeviceByUser(User user) {
		RLock rLock = redisson.getLock("deviceLock");
		
		List<Devices> deviceList = new ArrayList<>();
		Integer userId = user.getId();
		/*
		 * 在删除设备前查询出该用户拥有的设备
		 */
		deviceList = devicesMapper.selectDeviceByUserId(userId);
		
		if(!deviceList.isEmpty()) {
			try {
				boolean res = rLock.tryLock(10, 5, TimeUnit.SECONDS);
				if(res) {
					//删除设备
					devicesMapper.deleteDeviceByUserId(userId);
					
					//判断用户选择的产品在数据库中是否有对应产品存在
					IotProduct iotProduct = iotProductMapper.findIotProductById(user.getIotProductId());
					if(iotProduct != null) {
						for(Devices device : deviceList) {
							//删除物联网平台设备
//							iotManager.deleteDevice(iotProduct.getProductKey(),device.getDid());
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				rLock.unlock();
			}
		}
		
	}

	/**
	 * 根据用户拥有的设备在物联网平台上注册设备
	 * @param user
	 */
	@Override
	public void registerDevice(User user) {
		/*
		 * 将用户的拥有的设备名称(did)取出来
		 */
		List<Devices> deviceList = new ArrayList<>();
		deviceList = devicesMapper.selectDeviceByUserId(user.getId());
		
		//判断用户是否拥有设备
		if(!deviceList.isEmpty()) {
			//将用户需要更改的产品查询出来
			IotProduct iotProduct = iotProductMapper.findIotProductById(user.getIotProductId());
			for(Devices device : deviceList) {
				// 在物联网平台上注册相应设备
//				RegisterDeviceResponse response = iotManager.registerDevice(iotProduct.getProductKey(), device.getDid());
			}
		}
		
	}

	@Override
	public PageResult<Devices> userDevicePage(int pageNum, int pageSize, String deviceId, String mac) {
		// 获取登录账号
		String account = SecurityContextHolder.getContext().getAuthentication().getName();
				
		// 起始位置
		int pageNumber = (pageNum-1) * pageSize;
		List<Devices> deviceList = devicesMapper.queryUserDevice(pageNumber, pageSize, deviceId, mac, account);
		Long total = devicesMapper.getUserDeviceTotal(deviceId, mac, account);
		
		//返回分页数据
		PageResult<Devices> pageResult = new PageResult<Devices>();
		pageResult.setRows(deviceList);
		pageResult.setTotal(total);
		
		return pageResult;
	}

	@Override
	public Result<Object> unBundling(Devices device) {
		device.setUpdatedAt(new Date());
		devicesMapper.updateDeviceBundling(device);
		return ResultUtil.generate(CustomHttpStatus.SUCCESS);
	}

}
